package com.chat.api.web.service;

import com.chat.api.common.exception.ApiException;
import com.chat.api.exception.CoreExceptionEnum;
import com.chat.api.utils.ResultUtil;
import com.chat.api.utils.util.IdWorkerUtil;
import com.chat.api.utils.util.ParamUtil;
import com.chat.api.web.dao.BlogRepo;
import com.chat.api.web.po.BlogBean;
import com.chat.api.web.po.BlogGroupBean;
import com.chat.api.web.po.UserBean;
import com.chat.api.web.vo.BlogEntity;
import com.chat.api.web.vo.MessageEntity;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class BlogService {

    @Autowired
    private BlogRepo blogRepo;
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private BlogGroupService blogGroupService;

    /**
     * 获取博客主页
     * @param id
     * @param model
     */
    public ModelMap getList(Long id, ModelMap model) {
        try {
            UserBean bean = userService.findById(id);
            List<BlogEntity> entities = Lists.newArrayList();
            List<BlogEntity> entities2 = Lists.newArrayList();
            List<BlogBean> list = blogRepo.findAllByLimit(0);
            for (BlogBean blogBean : list) {
                BlogEntity entity = new BlogEntity();
                entity.setValue(blogBean);
                entities.add(entity);
            }
            List<BlogBean> list2 = blogRepo.findHotInfo();
            for (BlogBean blogBean : list2) {
                BlogEntity entity = new BlogEntity();
                entity.setValue(blogBean);
                entities2.add(entity);
            }
            model.addAttribute("user",bean);
            model.addAttribute("list",entities);
            model.addAttribute("list2",entities2);
            return model;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("获取博客列表失败！！！");
        }
    }

    /**
     * 保存并发布博客
     * @param blogEntity
     * @param request
     * @return
     */
    @Transactional(readOnly = false)
    public MessageEntity issue(BlogEntity blogEntity, HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute(session.getId());
            Long userIdL = ParamUtil.getLongParameter(userId, -1L);
            if (userIdL < 0){
                return new MessageEntity(CoreExceptionEnum.API_ACCESS_ERROR.getCode(),"登录已失效，请重新登录");
            }
//            //文章标题唯一性检验
//            BlogBean blogBean1 = blogRepo.selectByTitle(blogEntity.getTitle());
//            if (blogBean1 != null){
//                return ResultUtil.fail("标题已存在，请更换标题");
//            }

            BlogBean bean = blogRepo.selectByTitle(blogEntity.getTitle());
            blogEntity.setUserId(userId);
            UserBean userBean = userService.findById(userIdL);
            BlogBean blogBean = blogEntity.setBeanValue();
            Long id = 0L;
            if (bean == null) {
                id = IdWorkerUtil.getInstance().nextId();
            }else {
                id = bean.getId();
            }
            blogBean.setId(id);
            blogBean.setStatus("待审核");
            blogBean.setCreateDate(new Date());
            blogBean.setCreateBy(-1L);
            blogBean.setUpdateBy(-1L);
            blogBean.setUpdateDate(new Date());
            blogBean.setAuthorName(userBean.getName());
            blogRepo.save(blogBean);
            //开启博客审批流程
            activityService.openBlogApproval(blogBean);
            return ResultUtil.success("发布成功！审核结果将在24小时内公布");
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.fail("系统繁忙，请先将文章保存到草稿箱，稍后再试！！！");
        }
    }

    /**
     * 获取博客详情
     * @param id
     * @param model
     * @return
     */
    @Transactional(readOnly = false)
    public ModelMap getDetail(Long id, ModelMap model) {
        try {
            BlogBean one = blogRepo.findOneById(id);
            one.setViews(one.getViews()+1);
            blogRepo.save(one);
            //获取上下条博客信息
            BlogBean lastBean = blogRepo.findLastInfo(id);
            BlogEntity lastEntity = new BlogEntity();
            lastEntity.setId(String.valueOf(id));
            lastEntity.setTitle("无");
            if (lastBean != null) {
                lastEntity.setValue(lastBean);
            }
            BlogBean nextBean = blogRepo.findNextInfo(id);
            BlogEntity nextEntity = new BlogEntity();
            nextEntity.setId(String.valueOf(id));
            nextEntity.setTitle("无");
            if(nextBean != null) {
                nextEntity.setValue(nextBean);
            }
            List<BlogBean> blogBeans = blogRepo.findHotInfo();
            List<BlogEntity> list = Lists.newArrayList();
            for (BlogBean blogBean : blogBeans) {
                BlogEntity entity = new BlogEntity();
                entity.setValue(blogBean);
                list.add(entity);
            }
            BlogEntity entity = new BlogEntity();
            entity.setValue(one);
            model.addAttribute("blog",entity);
            model.addAttribute("list",list);
            model.addAttribute("last",lastEntity);
            model.addAttribute("next",nextEntity);
            return model;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("系统繁忙，请稍后再试");
        }
    }

    /**
     * 加载更多博客
     * @param pageNum
     * @return
     */
    public List<BlogEntity> getMoreList(Integer pageNum) {
        try {
            List<BlogEntity> entities = Lists.newArrayList();
            Integer pageNum2 = (pageNum-1) * 5;
            List<BlogBean> blogBeans = blogRepo.findAllByLimit(pageNum2);
            for (BlogBean blogBean : blogBeans) {
                BlogEntity entity = new BlogEntity();
                entity.setValue(blogBean);
                entities.add(entity);
            }
            return entities;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("加载更多失败！！！");
        }
    }

    //同步博客评论数量
    @Transactional(readOnly = false)
    public void saveRemarkCount(Long blogId) {
        try {
            BlogBean bean = blogRepo.findOneById(blogId);
            bean.setRemarkCount(bean.getRemarkCount()+1);
            blogRepo.save(bean);
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("同步博客评论数量失败！！！");
        }
    }

    /**
     * 获取阅读量前五博客
     * @return
     */
    public List<BlogBean> getReadTopFive() {
        try {
            return blogRepo.findHotInfo();
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("获取阅读量前五博客失败!!!");
        }
    }

    /**
     * 获取阅读量5名之后博客所有的阅读量
     * @return
     */
    public Integer getReadOther() {
        return blogRepo.findReadOther();
    }

    /**
     * 获取待审批博客列表
     * @return
     * @param type
     * @param userInfo
     */
    public MessageEntity getApprovalList(String type, UserBean userInfo) {
        try {
            List<BlogBean> list = Lists.newArrayList();
            List<BlogEntity> list2 = Lists.newArrayList();
            if (type.equals("0")){//获取自己博客
                list = blogRepo.findListByUserId(userInfo.getId());
            }else {//站主审批
                if (!userInfo.getUsername().equals("zhanzhu")){
                    return ResultUtil.fail("该用户没有权限");
                }
                list = blogRepo.findApprovalList();
            }
            for (BlogBean blogBean : list) {
                BlogEntity entity = new BlogEntity();
                entity.setValue(blogBean);
                list2.add(entity);
            }
            return ResultUtil.success(list2);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.fail("获取失败，垃圾代码！！！");
        }
    }

    @Transactional(readOnly = false)
    public void save(BlogBean blogBean) {
        try {
            blogRepo.save(blogBean);
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("博客bean保存失败！！！");
        }
    }

    public BlogBean getBeanById(Long id) {
        return blogRepo.findOneById(id);
    }

    /**
     * 审批博客
     * @param ids
     * @param result
     * @return
     */
    public MessageEntity approvalBlog(String ids, Integer result) {
        try {
            if (ids == null){
                return ResultUtil.fail("博客id不能为空");
            }
            Long id = ParamUtil.getLongParameter(ids, -1L);
            return activityService.approvalBlog(id,result);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.fail("审批失败，垃圾代码！！！");
        }
    }

    /**
     * 获取博客信息
     * @param ids
     * @return
     */
    public BlogBean editBlog(String ids) {
        try {
            Long id = ParamUtil.getLongParameter(ids, -1L);
            BlogBean oneById = blogRepo.findOneById(id);
            return oneById;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("系统繁忙，请稍后再试!!!");
        }
    }

    /**
     * 删除博客及其审批流程
     * @param ids
     * @return
     */
    public Boolean delBlog(String ids) {
        try {
            activityService.deleteByBlogId(ids);//删除相关审批流程
            blogRepo.deleteById(ParamUtil.getLongParameter(ids,-1L));
            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("博客删除失败!!!");
        }
    }

    //查看流程图
    public void getApprovalRate(String ids, HttpServletResponse response) {
        try {
            if (ids == null){
                throw new ApiException("博客id不能为空");
            }
            Long id = ParamUtil.getLongParameter(ids, -1L);
            activityService.getApprovalRate(id,response);
        }catch (Exception e){
            e.printStackTrace();
            throw new ApiException("审批失败，垃圾代码！！！");
        }
    }
}
